import cv2
import argparse
import tornado.web
import numpy as np
import LoggerDefault

ap = argparse.ArgumentParser()
ap.add_argument("-p", "--port", required=False)
args = vars(ap.parse_args())
port = args["port"]
if (port == None):
    port = 18003
else:
    port = int(port)

detect_obj = cv2.wechat_qrcode_WeChatQRCode()

def decode_wechat_cv_load_model(img):
    """
        使用 WeChatCv， 加载模型
    :param path:
    :return:
    """
    p1 = 'detect.prototxt'
    p2 = 'detect.caffemodel'
    p3 = 'sr.prototxt'
    p4 = 'sr.caffemodel'
    res, points = detect_obj.detectAndDecode(img)
    if len(res)==0:
        return ""
    else:
        return res[0]

class ClassifyRecognition(tornado.web.RequestHandler):
	async def post(self):
		body = self.request.body
		avatars = self.request.files
		img = np.asarray(bytearray(avatars.get("file")[0].get('body')), dtype="uint8")
		img = cv2.imdecode(img, cv2.IMREAD_COLOR)
		body=decode_wechat_cv_load_model(img);
		self.write({"code":"1","body":body})

application = tornado.web.Application([
    (r"/api/QrcodeRecognition", ClassifyRecognition)
])

if __name__ == '__main__':
	application.listen(port)
	tornado.ioloop.IOLoop.instance().start()